package com.yuedou.jylt.facelib.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicYuvToRGB;
import android.renderscript.Type;

public class NV21ToBitmap {

    private RenderScript rs;
    private ScriptIntrinsicYuvToRGB yuvToRgbIntrinsic;

    public NV21ToBitmap(Context context) {
        rs = RenderScript.create(context);
        yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));
    }

    public Bitmap nv21ToBitmap(byte[] nv21, int width, int height) {
        Type.Builder yuvType = new Type.Builder(rs, Element.U8(rs)).setX(nv21.length);
        Allocation in = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT);
        Type.Builder rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(width).setY(height);
        Allocation out = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT);
        in.copyFrom(nv21);
        yuvToRgbIntrinsic.setInput(in);
        yuvToRgbIntrinsic.forEach(out);
        Bitmap bmpout = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        out.copyTo(bmpout);
        Matrix matrix = new Matrix();
        matrix.postRotate(-90);
        matrix.postScale(-1, 1);
        Bitmap rotaBitmap1 = Bitmap.createBitmap(bmpout, 0, 0, width, height, matrix, false);

        System.out.println("width: " + width);
        System.out.println("height: " + height);

        int minleft = width / 4;
        int mintop = height / 4;

        System.out.println("minleft: " + minleft);
        System.out.println("mintop: " + mintop);

        int widthTemp = width - minleft * 3;
        int heightTemp = height - mintop * 3;
        System.out.println("widthTemp: " + widthTemp);
        System.out.println("heightTemp: " + heightTemp);
        Bitmap rotaBitmap = Bitmap.createBitmap(rotaBitmap1, minleft, 0, widthTemp, height);
        return rotaBitmap;

    }
}
